 
#include "byhh.h"

using namespace byhh_variables;

//This functin is to get a newer Topic list
void byhhBoard::refreshMe(){
    DEBUG_F();
    emit newStatus(211, tr("Check board '%1'...").arg(name));
    QHttp * http = new QHttp(server.host() , server.port(80));
    QObject::connect (http , SIGNAL(requestFinished(int , bool)) , this , SLOT(extractTopic(int , bool)));
    QString query = queryViewBoard.arg(id);
    int i = request(http, profile, query);
    httpMaps.insert(i , http);
}

//TODO:We haven't check the server's reply. Simply we think it success.
//Send a article to server.
void byhhBoard::send(QString title, QString signature, QString text){
    DEBUG_F();
    emit newStatus(201, tr("Sending a article..."));
    QHttp * http = new QHttp(server.host() , server.port(80));
    //QObject::connect (http , SIGNAL(requestFinished(int , bool)) , this , SLOT(extractTopic(int , bool)));
    QString post = sendNewPost.arg(id);
    QString content = sendContent.arg(title).arg(signature).arg(text);
    int i = request(http, profile, post, "POST", content);
    httpMaps.insert(i , http);
}

/*
we are about to split a topic data from like follow:

file=M.1237178296.A&start=3750>○   Linux中的字体如何设置才能最接近Windows </a><td><font color=black>16
*/
void byhhBoard::extractTopic(int num , bool error){
    ///To get topic list from a html
    //DEBUG_F();
    static bool NotFirstRefresh = false;
    QString html = fetchHtml(num , error);
    if (html == "") return;
    profile-> updateCookie(html);

    int pos = 0;
    byhhTopic * one = 0;
    QRegExp exp("file=([^&]+)&start[^>]+>[^ ]+\\s+([^ ]+[^<]*) [^\\d]+(\\d+)");
    while ( (pos = exp.indexIn(html , pos)) != -1) {
	one = new byhhTopic;
	Q_CHECK_PTR(one);
	one -> board = id;
	one -> id = exp.cap(1);
	one -> name = exp.cap(2);
	one -> reply = exp.cap(3).toInt();
	one -> setProfile( profile);
	one -> favorite = false;
	if (!addTopic(one))		//already exist
	    delete one;
	else if (NotFirstRefresh)
	    emit newStatus(212, tr("Got a new topic '%1' on board '%2'").arg(one->name).arg(name));
	pos += exp.matchedLength();
    }
    emit refreshFinished(false);
    NotFirstRefresh = true;
}
